package com.open.capacity.interceptor;

import com.open.capacity.commons.Globals;
import com.open.capacity.license.LicenseVerify;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * LicenseCheckInterceptor
 *
 * @date 2018/4/25
 * @since 1.0.0
 */
@Component
public class LicenseCheckInterceptor extends HandlerInterceptorAdapter {
    private static Logger logger = LogManager.getLogger(LicenseCheckInterceptor.class);


    /**
     * 证书生成路径
     */
    @Value("${license.licensePath:D:/tonghui/reimburse/files/license.txt}")
    private String licensePath;

    @Value("${license.closed:0}")
    private Integer licenseClosed;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (licenseClosed != null && licenseClosed.equals(1)) {
            return true;
        }

        LicenseVerify licenseVerify = new LicenseVerify();
        boolean verifyResult = false;
        //校验证书是否有效

        try {
            verifyResult = licenseVerify.verify(licensePath);
        } catch (Exception e) {
            logger.error("校验授权码失败：", e.getMessage());
        }

        if (verifyResult) {
            Globals.authorized = true;
        } else {
            Globals.authorized = false;
            response.setCharacterEncoding("utf-8");
            response.getWriter().write("Your certificate is invalid, please check whether the server is authorized or reapply for a certificate!");

            return false;
        }

        return true;
    }

}
